package com.zh.modules.app.service.impl;

import com.zh.common.exception.ServiceException;
import com.zh.modules.app.entity.OrdersDO;
import com.zh.modules.app.entity.UserDO;
import com.zh.modules.app.entity.vo.OrdersVO;
import com.zh.modules.app.mapper.UserMapper;
import com.zh.modules.app.repository.OrdersRepository;
import com.zh.modules.app.service.OrderService;
import com.zh.modules.app.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.Date;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersRepository ordersRepository;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Integer queryUnitPrice(OrdersVO ordersVO) {
        if (ordersVO.getDayNum() == null || ordersVO.getDayNum().equals(30)) {
            return 120;
        }
        return 240;
    }

    @Override
    @Transactional
    public Boolean createOrder(OrdersVO ordersVO) {
        Integer userId = JwtUtils.getUser().getId();
        UserDO userDO = userMapper.selectById(userId);
        if (userDO.getBalance() < ordersVO.getTotalPrice()) {
            throw new ServiceException("Insufficient Balance", "余额不足");
        }
        //扣减余额
        int update = userMapper.deductBalance(userId, ordersVO.getTotalPrice());
        if (update == 0) {
            throw new ServiceException("Insufficient Balance", "余额不足");
        }
        OrdersDO orderDO = new OrdersDO();
        BeanUtils.copyProperties(ordersVO, orderDO);
        orderDO.setUserId(userId);
        orderDO.setPayTime(new Date());
        orderDO.setOrderNo(getOrderNo());
        orderDO.setStatus(1);
        ordersRepository.save(orderDO);
        return true;
    }

    public static String getOrderNo() {
        try {
            // 生成随机字符串
            SecureRandom random = new SecureRandom();
            byte[] randomBytes = new byte[16];
            random.nextBytes(randomBytes);
            String randomString = bytesToHex(randomBytes);

            // 哈希处理
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] hashBytes = digest.digest(randomString.getBytes());
            String hashCode = bytesToHex(hashBytes);
            return hashCode;
        } catch (NoSuchAlgorithmException e) {
            log.error("getOrderNo error", e);
            throw new ServiceException("未知异常");

        }
    }

    // 将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }
}
